package user.interfaces.controller;

import user.domain.model.User;
import user.application.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService service;

    // 新增用户
    @PostMapping
    public User create(@RequestBody User user) {
        return service.createUser(user);
    }

    // 查询所有用户
    @GetMapping
    public List<User> list() {
        return service.listUsers();
    }

    // 根据 ID 查询用户
    @GetMapping("/{id}")
    public Optional<User> getById(@PathVariable Long id) {
        return service.getUser(id);
    }

    // 根据 ID 修改用户
    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        System.out.println("📥 收到更新用户请求，ID: " + id);
        return service.updateUser(id, user);
    }

    // 根据 ID 删除用户
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        service.deleteUser(id);
    }

    @GetMapping("/current")
    public ResponseEntity<User> getCurrentUser(@RequestHeader("X-Username") String username) {
        return service.getUserByUsername(username)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body(null));
    }


    // 注册
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        try {
            service.registerUser(user);
            return "User registered successfully";
        } catch (RuntimeException e) {
            return "Registration failed: " + e.getMessage();
        }
    }

    // 登录
    @PostMapping("/login")
    public User login(@RequestBody Map<String, String> body) {
        return service.login(body.get("email"), body.get("password"));
    }

    //  修改密码
    @PutMapping("/reset-password")
    public String resetPassword(@RequestBody Map<String, String> body) {
        try {
            service.resetPassword(body.get("email"), body.get("password"));
            return "Password changed successfully";
        } catch (RuntimeException e) {
            return "Change password failed: " + e.getMessage();
        }
    }


    // 正确写法，路径与前端一致，支持 limit 参数
    @GetMapping("/notifications")
    public List<String> getNotifications(@RequestParam(defaultValue = "5") int limit) {
        List<String> all = List.of("新用户注册", "系统更新", "新订单", "待审核用户", "有新反馈");
        return all.subList(0, Math.min(limit, all.size())); // ⭐️ 防止 limit > all.size() 导致 IndexOutOfBoundsException
    }



}
